<script setup>
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import HeaderPage from '../components/common/headerPage.vue'
import FooterPage from '../components/common/footerPage.vue'

const route = useRoute()
const router = useRouter()

// 基础状态管理
const searchResults = ref([])
const loading = ref(false)
const totalResults = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const keyword = ref('')

// 执行搜索
const performSearch = async () => {
  if (!keyword.value.trim()) return

  try {
    loading.value = true

    // 构建查询参数
    const params = {
      q: keyword.value,
      page: currentPage.value,
      page_size: pageSize.value
    }

    // 调用API获取数据
    const response = await request.get('/search/search/', { params })

    // 处理响应数据
    if (response.data) {
      searchResults.value = response.data.results || []
      totalResults.value = response.data.total || 0
    } else {
      ElMessage.error('搜索失败，请稍后重试')
    }
  } catch (err) {
    console.error('搜索请求失败:', err)
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 跳转到商品详情
const goToProductDetail = (product) => {
  router.push(`/goods/${product.id}`)
}

// 处理页面变化
const handlePageChange = (page) => {
  currentPage.value = page
  performSearch()
}

// 处理页面大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1 // 重置为第一页
  performSearch()
}

// 监听路由参数变化
watch(() => route.query.q, (newQ) => {
  keyword.value = newQ || ''
  if (keyword.value) {
    currentPage.value = 1 // 重置为第一页
    performSearch()
  }
}, { immediate: true })
</script>

<template>
  <HeaderPage style="background-color: #fff;" />
  <div class="search-result-page">
    <!-- 公共头部 -->
     
    <div class="search-result-content">
      <!-- 搜索标题 -->
      <div class="search-header">
        <h2>搜索结果：{{ keyword }}</h2>
        <p v-if="totalResults > 0">找到 {{ totalResults }} 个商品</p>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-text">搜索中...</div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="totalResults === 0 && keyword" style="text-align: center;">
        未找到相关商品
      </div>

      <!-- 商品网格 -->
      <div class="product-grid" v-else>
        <div v-for="product in searchResults" :key="product.id" class="product-item"
          @click="goToProductDetail(product)">
          <!-- 商品图片 -->
          <div class="product-image">
            <img :src="product.image || product.image_url || '/logo.png'" :alt="product.name || product.title || '商品图片'"
              loading="lazy">
          </div>

          <!-- 商品信息 -->
          <div class="product-info">
            <h3 class="product-name">{{ product.name || product.title || '未命名商品' }}</h3>
            <p class="product-price">¥{{ product.price || 0 }}</p>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="totalResults > 0">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
          layout="total, sizes, prev, pager, next" :total="totalResults" :page-size="pageSize"
          :page-sizes="[10, 20, 30, 40]" @current-change="handlePageChange" @size-change="handleSizeChange"
          background />
      </div>
    </div>
    <!-- 公共页脚 -->
    <FooterPage />
  </div>
</template>

<style scoped>
.search-result-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.search-result-content {
  flex: 1;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  width: 100%;
  background-color: #ffffff;
  margin-top: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.search-header h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.search-header p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.loading-container {
  text-align: center;
  padding: 80px 20px;
  color: #666;
  font-size: 16px;
}

.empty-container {
  margin: 60px 0;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.product-item {
  border: 1px solid #e8e8e8;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #ffffff;
}

.product-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.product-image {
  text-align: center;
  margin-bottom: 15px;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.product-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.product-info {
  text-align: left;
}

.product-name {
  font-size: 16px;
  color: #333;
  margin: 0 0 10px 0;
  height: 40px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
  margin: 0;
}

.pagination {
  margin-top: 20px;
  text-align: center;
  padding: 10px 0;
}

:deep(.el-pagination) {
  justify-content: center;
  font-size: 12px;
}

:deep(.el-pagination .el-pagination__total) {
  margin-right: 8px;
  color: #606266;
  font-size: 12px;
}

:deep(.el-pagination .el-select) {
  font-size: 12px;
}

:deep(.el-pagination .el-pagination__sizes) {
  margin-right: 8px;
}

:deep(.el-pagination .el-pagination__sizes .el-input__wrapper) {
  height: 24px;
  font-size: 12px;
}

:deep(.el-pagination .el-pager li) {
  min-width: 24px;
  height: 24px;
  line-height: 24px;
  margin: 0 2px;
  border-radius: 3px;
  border: 1px solid #dcdfe6;
  font-size: 12px;
}

:deep(.el-pagination .el-pager li:hover:not(.disabled)) {
  color: #409eff;
  border-color: #c6e2ff;
}

:deep(.el-pagination .el-pager li.active) {
  background-color: #409eff;
  color: #fff;
  border-color: #409eff;
}

:deep(.el-pagination button) {
  min-width: 24px;
  height: 24px;
  border-radius: 3px;
  border: 1px solid #dcdfe6;
  margin: 0 3px;
  font-size: 12px;
  padding: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-result-content {
    padding: 15px;
    margin-top: 10px;
    margin-bottom: 10px;
  }

  .product-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 15px;
  }

  .product-image {
    height: 160px;
  }

  .product-name {
    font-size: 14px;
  }

  .product-price {
    font-size: 16px;
  }

  .search-header h2 {
    font-size: 20px;
  }
}
</style>


